﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using YiSha.Admin.Web.Controllers;
using YiSha.Business.OrganizationManage;
using YiSha.Business.Test;
using YiSha.Entity.OrganizationManage;
using YiSha.Entity.Test;
using YiSha.Model.Param.Test;
using YiSha.Util.Model;
using YiSha.Web.Code;

namespace YiSha.Admin.Web.Areas.PMCManage.Controllers
{

    [Area("PMCManage")]
    public class ProcessController : BaseController
    {

        private readonly ProcessBLL processBLL = new ProcessBLL();

        private readonly DepartmentBLL departmentBLL = new DepartmentBLL();

        #region 视图功能
        [AuthorizeFilter("pmc:process:manage")]
        public IActionResult Manage()
        {
            return View();
        }

        [AuthorizeFilter("pmc:process:add")]
        public IActionResult ProcessAdd()
        {
            return View();
        }
        #endregion

        #region 获取数据接口
        [HttpPost]
        [AuthorizeFilter("pmc:process:manage")]//工序管理权限
        public async Task<IActionResult> GetListJson([FromForm] ProcessParam param)
        {
            TData<List<ProcessEntity>> obj = await processBLL.GetListJson(param);
            if (param.IsTree)
            {
                // 将扁平数据转换为树形结构
                List<ProcessEntity> treeData = ConvertToTree(obj.Data);
                obj.Data = treeData;
            }
            return Json(obj);
        }

        [HttpGet]
        [AuthorizeFilter("pmc:schedule:addView")]//排产权限
        public async Task<IActionResult> GetListJsonByDepartmentRemark()//根据用户部门备注来获取工序列表（PMC使用）
        {
            OperatorInfo user = await Operator.Instance.Current();
            long departmentId = (long)user.DepartmentId;//获取当前用户部门Id
            TData<DepartmentEntity> departmentEntity = await departmentBLL.GetEntity(departmentId);//根据部门id查出所属部门
            //根据部门的备注查询有权限的非顶级工序
            TData<List<ProcessEntity>> obj = await processBLL.GetListJsonByDepartmentRemark(departmentEntity.Data.Remark);
            return Json(obj);
        }

        [HttpGet]
        [AuthorizeFilter("pmc:schedule:upRealNumber")]//报工权限
        public async Task<IActionResult> GetListJsonByUserId()//根据用户Id来获取工序列表（工序负责人使用）
        {
            OperatorInfo user = await Operator.Instance.Current();
            TData<List<ProcessEntity>> obj = await processBLL.GetListJsonByUserId(user.UserId);
            return Json(obj);
        }
        #endregion

        #region 更新数据接口

        #endregion

        #region 新增数据接口
        [HttpPost]
        [AuthorizeFilter("pmc:process:add")]//新增工序权限
        public async Task<IActionResult> Add([FromForm] ProcessEntity processEntity)
        {
            TData obj = new TData();
            int number = await processBLL.Add(processEntity);
            if (number==1)//受影响的行数为1，表示新增成功
            {
                obj.Tag = 1;
                obj.Message = "新增成功";
            } else
            {
                obj.Tag = 0;
                obj.Message = "新增失败";
            }
            return Json(obj);
        }
        #endregion

        #region 私有方法 - 数据转换
        /// <summary>
        /// 将扁平的工序数据转换为树形结构（不使用字典）
        /// </summary>
        /// <param name="flatData">扁平的工序数据列表</param>
        /// <returns>树形结构的工序数据</returns>
        private List<ProcessEntity> ConvertToTree(List<ProcessEntity> flatData)
        {
            if (flatData == null || flatData.Count == 0)
                return new List<ProcessEntity>();

            // 创建数据的副本，避免修改原始数据
            List<ProcessEntity> data = new List<ProcessEntity>();
            foreach (var item in flatData)
            {
                // 深拷贝每个对象，避免引用问题
                ProcessEntity process = new ProcessEntity
                {
                    Id = item.Id,
                    Name = item.Name,
                    ParentId = item.ParentId,
                    DepartmentRemark = item.DepartmentRemark,
                    UserId = item.UserId,
                    Children = new List<ProcessEntity>() // 初始化子节点集合
                };
                data.Add(process);
            }

            // 构建树形结构
            List<ProcessEntity> treeData = new List<ProcessEntity>();

            // 找出所有根节点（ParentId为null或0）
            foreach (var process in data)
            {
                if (process != null && (process.ParentId == null || process.ParentId == 0))
                {
                    treeData.Add(process);
                    // 递归添加子节点
                    AddChildNodes(process, data);
                }
            }

            // 如果没有根节点（所有节点都有ParentId），则返回所有节点作为根节点
            if (treeData.Count == 0)
            {
                treeData.AddRange(data);
            }

            return treeData;
        }

        /// <summary>
        /// 递归为节点添加子节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="allNodes">所有节点列表</param>
        private void AddChildNodes(ProcessEntity parentNode, List<ProcessEntity> allNodes)
        {
            if (parentNode == null || allNodes == null || allNodes.Count == 0)
                return;

            // 确保子节点集合已初始化
            parentNode.Children ??= new List<ProcessEntity>();

            // 查找所有ParentId等于当前节点Id的子节点
            foreach (var node in allNodes)
            {
                if (node != null && node.ParentId.HasValue && node.ParentId.Value == parentNode.Id)
                {
                    parentNode.Children.Add(node);
                    // 递归添加子节点的子节点
                    AddChildNodes(node, allNodes);
                }
            }
        }
        #endregion

    }
}
